<?php

namespace Biz\tools;

use Biz\cache\wiki\JdUnionUrl;
use Doraemon\pockets\config\IniConfig;
use Doraemon\pockets\constInterface\ApiCode;
use Doraemon\tools\Curl;
use Doraemon\tools\Log;
use JdMediaSdk\JdFatory;

class JdUnion implements ApiCode
{
    const PID = '1001597880_1820317787_1824065583';
    const UNION_ID = '1001597880';
    const SITE_ID = '1820317787';
    const POSITION_ID = '1824065583';

    const _CONFIG_FILE_ = 'jd_union';

    const PLATFORM_PC = 1;
    const PLATFROM_MOBILE = 2;

    const GET_JD_PRICE_URL = 'https://p.3.cn/prices/mgets';

    private static $app = null;

    private static function _getAppConfig()
    {
        return IniConfig::getConfigFile(static::_CONFIG_FILE_);
    }

    public static function getApp()
    {
        if (is_null(self::$app)) {
            $config = self::_getAppConfig();
            $app = new JdFatory([
                'appkey' => $config['default']['appkey'],
                'appSecret' => $config['default']['secretKey'],
                'unionId' => self::UNION_ID,
                'positionId' => self::POSITION_ID,
                'siteId' => self::SITE_ID,
                'isCurl' => true,
            ]);
            self::$app = $app;
        }
        return self::$app;
    }

    public static function getItemInfo($itemId, $bigField = true)
    {
        $itemInfo = [];
        $app = self::getApp();
        $result = $app->good->info((string)$itemId);
        if ($result == false) {
            Log::error($app->getError());
        } else {
            $itemInfo = $result[0];
        }
        if ($bigField) {
            $bigFields = ['categoryInfo', 'imageInfo', 'detailImages'];
            $bigItemInfo = self::getBigItemInfo([$itemId], $bigFields);
            //sku上下架状态 1：上架(可搜索，可购买)， 0：下架(可通过skuid搜索，不可购买)， 2：可上架（可通过skuid搜索，不可购买）， 10：pop 删除（不可搜索，不可购买））
            $skuStatus = isset($bigItemInfo['skuStatus']) ? $bigItemInfo['skuStatus'] : 1;
            foreach ($bigFields as $field) {
                if (!isset($bigItemInfo[$field]) || empty($bigItemInfo[$field])) {
                    unset($bigItemInfo[$field]);
                }
            }
            if ($itemInfo || $bigItemInfo) {
                $itemInfo['skuId'] = $itemId;
                $itemInfo['goodsName'] = ($bigItemInfo && $bigItemInfo['skuName']) ? $bigItemInfo['skuName'] : '';
                $itemInfo['cidName'] = ($bigItemInfo && $bigItemInfo['categoryInfo'] && $bigItemInfo['categoryInfo']['cid1Name']) ? $bigItemInfo['categoryInfo']['cid1Name'] : '';
                $itemInfo['detailImages'] = ($bigItemInfo && $bigItemInfo['detailImages']) ? explode(',', $bigItemInfo['detailImages']) : [];
                $itemInfo['imageList'] = ($bigItemInfo && $bigItemInfo['imageInfo'] && $bigItemInfo['imageInfo']['imageList']) ? array_column($bigItemInfo['imageInfo']['imageList'], 'url') : [];
                $itemInfo['skuStatus'] = $skuStatus;
            }
        }
        return $itemInfo;
    }

    /**
     * @param array $itemId
     * @param array $fieldList 查询域集合，不填写则查询全部，目目前支持：categoryInfo（类目信息）,imageInfo（图片信息）,baseBigFieldInfo（基础大字段信息）,bookBigFieldInfo（图书大字段信息）,videoBigFieldInfo（影音大字段信息）,detailImages（商详图）
     * @return false
     * @throws \Exception
     */
    public static function getBigItemInfo(array $itemId, array $fieldList = [])
    {
        $app = self::getApp();
        $result = $app->good->bigFieldQuery($itemId, $fieldList);
        if ($result == false) {
            Log::error($app->getError());
            return false;
        } else {
            return $result[0];
        }

    }

    public static function tryGetItemUnionUrl($itemId)
    {
        $jdUnionUrl = JdUnionUrl::getItem($itemId);
        if ($jdUnionUrl) {
            return $jdUnionUrl['url'];
        } else {
            $jdUnionUrl = ['url' => false];
            $expire = 86400;
            $itemInfo = self::getItemInfo($itemId, false);
            if ($itemInfo) {
                $materialUrl = (isset($itemInfo['materialUrl']) && $itemInfo['materialUrl']) ? $itemInfo['materialUrl'] : RealUrl::formatLink($itemId, RealUrl::URL_TYPE_JD);
                $app = self::getApp();
                $result = $app->link->get($materialUrl);
                if ($result == false) {
                    Log::error($app->getError());
                    $jdUnionUrl['url'] = $materialUrl;
                    $expire = 86400;
                } else {
                    $jdUnionUrl['url'] = $result['clickURL'];
                    $expire = $jdUnionUrl['url'] ? JdUnionUrl::_CACHE_EXPIRE_TIME : 86400;
                }
            }
            JdUnionUrl::setItem($itemId, $jdUnionUrl, $expire);
            return $jdUnionUrl['url'];
        }

    }

    /**
     * @param $startTime 开始时间 格式yyyy-MM-dd HH:mm:ss
     * @param $endTime 结束时间 格式yyyy-MM-dd HH:mm:ss，与startTime间隔不超过1小时,
     * @param $pageIndex 页码
     * @param $type 订单时间查询类型(1：下单时间，2：完成时间（购买用户确认收货时间），3：更新时间
     * @param $pageSize 每页包含条数，上限为500,
     * @return void
     * @throws \Exception
     */
    public static function getOrder($startTime, $endTime, $pageIndex = 1, $type = 1, $pageSize = 20)
    {
        $params = [
            'pageIndex' => $pageIndex,//页码
            'pageSize' => $pageSize,//每页包含条数，上限为500,
            'type' => $type,//订单时间查询类型(1：下单时间，2：完成时间（购买用户确认收货时间），3：更新时间
            'startTime' => $startTime,
            'endTime' => $endTime,//结束时间 格式yyyy-MM-dd HH:mm:ss，与startTime间隔不超过1小时,
            'fields' => 'goodsInfo,categoryInfo',//支持出参数据筛选，逗号','分隔，目前可用：goodsInfo（商品信息）,categoryInfo(类目信息）
        ];
        $app = JdUnion::getApp();
        $res = $app->promotion->orderRow($params);
        return $res;
    }

    /**
     * 京东获取价格
     * @param $skuIds
     * @return array
     */
    public static function getJDPrice($skuIds)
    {
        $skuIds = !is_array($skuIds) ? [$skuIds] : $skuIds;
        $priceArr = [];
        $prefix = 'J_';
        $urlQueryParams = '';
        foreach ($skuIds as $skuId) {
            $str = $prefix . $skuId;
            if (empty($urlQueryParams)) {
                $urlQueryParams = $str;
            } else {
                $urlQueryParams .= ',' . $str;
            }
        }
        $url = self::GET_JD_PRICE_URL . '?skuIds=' . $urlQueryParams;
        $result = Curl::Request('GET', $url, [], true);
        if ($result && isset($result['json']) && $result['json']) {
            foreach ($result['json'] as $row) {
                $id = substr($row['id'], strlen($prefix));
                $priceArr[$id] = (int)$row['p'] > 0 ? $row['p'] : 0;
            }
        }
        return $priceArr;
    }

}